import json
import shutil
from utils.yamltool import BasePath

import os

ALLURE_REPORTS_DIR = os.path.join(BasePath, 'reports')
ALLURE_DIR = os.path.join(BasePath, 'temp')


def get_dirname():
	history_file = os.path.join(ALLURE_REPORTS_DIR, "history.json")
	if os.path.exists(history_file):
		with open(history_file) as f:
			li = eval(f.read())
		# 根据构建次数进行排序，从大到小
		li.sort(key=lambda x: x['buildOrder'], reverse=True)
		# 返回下一次的构建次数，所以要在排序后的历史数据中的buildOrder+1
		return li[0]["buildOrder"] + 1, li
	else:
		# 首次进行生成报告，肯定会进到这一步，先创建history.json,然后返回构建次数1（代表首次）
		with open(history_file, "w") as f:
			pass
		return 1, None


def update_trend_data(dirname, old_data):
	""" dirname：构建次数 old_data：备份的数据 update_trend_data(get_dirname()) """
	WIDGETS_DIR = os.path.join(ALLURE_REPORTS_DIR, f"{str(dirname)}/widgets")
	# 读取最新生成的history-trend.json数据
	with open(os.path.join(WIDGETS_DIR, "history-trend.json")) as f:
		data = f.read()

	new_data = eval(data)
	if old_data is not None:
		new_data[0]["buildOrder"] = old_data[0]["buildOrder"] + 1
	else:
		old_data = list()
		new_data[0]["buildOrder"] = 1
	# 给最新生成的数据添加reportUrl key，reportUrl要根据自己的实际情况更改
	new_data[0]["reportUrl"] = f"/{dirname}/index.html"
	# 把最新的数据，插入到备份数据列表首位
	old_data.insert(0, new_data[0])
	# 把所有生成的报告中的history-trend.json都更新成新备份的数据old_data，这样的话，点击历史趋势图就可以实现新老报告切换
	for i in range(1, dirname + 1):
		with open(os.path.join(ALLURE_REPORTS_DIR, f"{str(i)}/widgets/history-trend.json"), "w+") as f:
			f.write(json.dumps(old_data))
	# 把数据备份到history.json
	history_file = os.path.join(ALLURE_REPORTS_DIR, "history.json")
	with open(history_file, "w+") as f:
		f.write(json.dumps(old_data))
	return old_data, new_data[0]["reportUrl"]


def copy_files(source_dir, destination_dir):
	for root, dirs, files in os.walk(source_dir):
		for file in files:
			source_file_path = os.path.join(root, file)
			relative_path = os.path.relpath(source_file_path, source_dir)
			destination_file_path = os.path.join(destination_dir, relative_path)

			# 创建目标文件所在的目录（如果不存在）
			os.makedirs(os.path.dirname(destination_file_path), exist_ok=True)

			shutil.copy2(source_file_path, destination_file_path)


if __name__ == '__main__':
	command = f'pytest {BasePath} -s --alluredir={ALLURE_DIR}'
	os.system(command)
	# 环境描述
	shutil.copy('./environment.xml', './temp')
	# 先调用get_dirname()，获取到这次需要构建的次数
	buildOrder, old_data = get_dirname()
	# 再执行命令行
	command = f"allure generate --lang zh {ALLURE_DIR} -o {os.path.join(ALLURE_REPORTS_DIR, str(buildOrder))}  --clean"
	os.system(command)
	# 执行完毕后再调用update_trend_data()
	all_data, reportUrl = update_trend_data(buildOrder, old_data)
	copy_files(os.path.join(ALLURE_REPORTS_DIR, str(buildOrder)), ALLURE_REPORTS_DIR)
